using System;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
using System.Configuration;
using Microsoft.SharePoint.Utilities;
using System.Reflection;
using System.Collections;

namespace CKS.FormsBasedAuthentication
{
    /// <summary>
    /// A feature event handler for web parts, when deactivating it removes the web part from the web part gallery
    /// </summary>
    class GenericWebPartFeatureReceiver : SPFeatureReceiver
    {

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = null;
            try
            {
                site = properties.Feature.Parent as SPSite;
                using (SPWeb web = site.RootWeb)
                {
                    SPList list = web.Lists["Web Part Gallery"];

                    // go through the items in reverse
                    for (int i = list.ItemCount - 1; i >= 0; i--)
                    {
                        // format name to look like a feature name
                        string webpartName = list.Items[i].Name;
                        webpartName = webpartName.Substring(0, webpartName.IndexOf('.')) + "WebPart";

                        // delete web parts that have been added
                        if (properties.Feature.Definition.DisplayName == webpartName)
                        {
                            list.Items[i].Delete();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.LogError(ex);
            }
            finally
            {
                if (site != null)
                    site.Dispose();
            }
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
